package com.scheduled;

import com.mrobuy.jdvc.dao.CommonDao;
import com.mrobuy.jdvc.entity.Task;
import com.mrobuy.jdvc.entity.VCShelvesTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 上架任务定时处理
 *
 *  初始 -> 等待采集完成/商品导入中
 */
@Component
public class ShelvesTaskCheckTask {

    private static Logger LOG = LoggerFactory.getLogger(ShelvesTaskCheckTask.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private CommonDao commonDao;

    @Scheduled(fixedRate = 1000*60)
    public void exec() {

        if ( !TaskSwitch.TASK_CHECK.get() ) {
            return;
        }

        List<VCShelvesTask> shelvesTasks = jdbcTemplate.query("select * from VC_SHELVES_TASK  where STATE in (?, ?) ", new Object[]{"0", "1"}, new BeanPropertyRowMapper(VCShelvesTask.class));
        if ( shelvesTasks==null || shelvesTasks.size()==0 ) {
            LOG.info("[上架任务状态检测]无上架任务处理");
            return;
        }

        for (VCShelvesTask shelvesTask : shelvesTasks) {
            LOG.info(shelvesTask.getName() + " ==> " + shelvesTask.getState());
            VCShelvesTask update = new VCShelvesTask();
            update.setId(shelvesTask.getId());
            try {
                Task task =  (Task) jdbcTemplate.queryForObject("select * from TASK where ID = ? ", new Object[]{shelvesTask.getSource().trim()},  new BeanPropertyRowMapper(Task.class));
                if ( task==null ) {
                    throw  new RuntimeException("[Task: " + shelvesTask.getSource().trim() + "]采集任务未找到.");
                }
                if ( !"success".equalsIgnoreCase(task.getStatus()) ) {
                    update.setState("1");
                } else {
                    LOG.info("[上架任务][{}]数据已采集完成.", shelvesTask.getName());
                    update.setState("2");
                }
                commonDao.update(update, false);
            } catch (Exception e) {
                LOG.error(e.getMessage(), e.getCause());
            }
        }
    }
}
